import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import userConfig from '@src/config/user.config';
import { UserEntity } from '@src/modules/system/user/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class InitDbServices {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  onModuleInit() {
    console.log('初始化数据库');
    this.initAccount();
  }

  /**
   * @description: 初始化账号
   */
  private async initAccount(): Promise<void> {
    const username: string = userConfig.defaultUsername;
    const password: string = userConfig.adminPassword;
    const isExist = await this.userRepository.findOne({ where: { username } });
    // 不存在
    if (!isExist) {
      const account = this.userRepository.create({
        username,
        password,
        isSuper: 1,
      });
      await this.userRepository.save(account);
    }
  }
}
